#include "selectionmanager.h"
#include "elementselector.h"
#include <QPainter>
#include <QApplication>

#include <Element>
#include <Document>

#include "src/drawingview.h"

SelectionManager::SelectionManager(QObject *parent) :
    QObject(parent)
{

}

void SelectionManager::drawSelector() const
{
    if(m_selector)
    {
        m_selector->draw();
    }
}

void SelectionManager::drawSelectionMarkers() const
{
}

void SelectionManager::setSelector(QPointer<ElementSelector> selector)
{
    m_selector = selector;
}

bool SelectionManager::isSelected(QPointer<Element> element) const
{
    return m_selection.contains(element);
}

bool SelectionManager::isAllSelected() const
{
    QPointer<DrawingView> view = qobject_cast<DrawingView*>(parent());
    QPointer<Document> doc = view->document();

    return (doc->elements().size() == m_selection.size());
}

bool SelectionManager::isNoneSelected() const
{
    return m_selection.size() == 0;
}

void SelectionManager::updateSelection()
{
}

void SelectionManager::select(QPointer<Element> element)
{
    if(!m_selection.contains(element))
    {
        m_selection.append(element);
        emit selectionChanged();
    }
}

void SelectionManager::deselect(QPointer<Element> element)
{
    if(m_selection.contains(element))
    {
        m_selection.removeOne(element);
        emit selectionChanged();
    }
}

void SelectionManager::selectAll()
{
    QPointer<DrawingView> view = qobject_cast<DrawingView*>(parent());
    QPointer<Document> doc = view->document();

    if(!isAllSelected())
    {
        // OPTIMIZE
        m_selection.clear();

        foreach(QPointer<Element> element, doc->elements())
        {
            m_selection.append(element);
        }

        emit selectionChanged();
    }
}

void SelectionManager::deselectAll()
{
    QPointer<DrawingView> view = qobject_cast<DrawingView*>(parent());

    if(!isNoneSelected())
    {
        m_selection.clear();
        emit selectionChanged();
    }
}

void SelectionManager::invertSelection()
{
    QPointer<DrawingView> view = qobject_cast<DrawingView*>(parent());
    QPointer<Document> doc = view->document();

    if(isAllSelected())
    {
        deselectAll();
    }
    else if(isNoneSelected())
    {
        selectAll();
    }
    else
    {

    }
}
